/**
 * DI 装饰器
 * 
 * 提供便捷的装饰器用于依赖注入
 * 
 * @author AI Assistant
 * @date 2025-11-27
 */

import { container, ServiceLifetime, ServiceIdentifier } from './DIContainer';
import { Log } from '../logger/LoggerGlobal';

/**
 * 注入装饰器元数据
 */
const INJECT_METADATA_KEY = Symbol('inject');
const INJECTABLE_METADATA_KEY = Symbol('injectable');

/**
 * Injectable 装饰器 - 标记类可以被注入
 * 
 * @param lifetime 生命周期（默认：单例）
 * @param identifier 服务标识符（默认：类本身）
 */
export function Injectable(
    lifetime: ServiceLifetime = ServiceLifetime.SINGLETON,
    identifier?: ServiceIdentifier
) {
    return function <T extends { new (...args: any[]): any }>(constructor: T) {
        // 自动注册到容器
        const serviceId = identifier || constructor;
        
        switch (lifetime) {
            case ServiceLifetime.SINGLETON:
                container.registerSingleton(serviceId, constructor);
                break;
            case ServiceLifetime.TRANSIENT:
                container.registerTransient(serviceId, constructor);
                break;
            case ServiceLifetime.SCOPED:
                container.registerScoped(serviceId, constructor);
                break;
        }
        
        Log.general.debug('Injectable 服务已注册', {
            name: constructor.name,
            lifetime
        });
        
        return constructor;
    };
}

/**
 * Inject 装饰器 - 属性注入
 * 
 * @param identifier 服务标识符
 */
export function Inject(identifier: ServiceIdentifier) {
    return function (target: any, propertyKey: string) {
        // 定义 getter（延迟解析）
        Object.defineProperty(target, propertyKey, {
            get: function () {
                return container.resolve(identifier);
            },
            enumerable: true,
            configurable: true
        });
    };
}

/**
 * LazyInject 装饰器 - 延迟属性注入（缓存实例）
 * 
 * @param identifier 服务标识符
 */
export function LazyInject(identifier: ServiceIdentifier) {
    return function (target: any, propertyKey: string) {
        let instance: any = null;
        
        Object.defineProperty(target, propertyKey, {
            get: function () {
                if (!instance) {
                    instance = container.resolve(identifier);
                }
                return instance;
            },
            enumerable: true,
            configurable: true
        });
    };
}

/**
 * PostConstruct 装饰器 - 构造后调用
 */
export function PostConstruct() {
    return function (
        target: any,
        propertyKey: string,
        descriptor: PropertyDescriptor
    ) {
        const originalMethod = descriptor.value;
        
        // 修改构造函数，在构造后调用该方法
        const originalConstructor = target.constructor;
        target.constructor = function (...args: any[]) {
            const instance = new originalConstructor(...args);
            setTimeout(() => originalMethod.call(instance), 0);
            return instance;
        };
    };
}

/**
 * 服务标识符符号
 */
export const ServiceIdentifiers = {
    // 核心服务
    GameApplication: Symbol('GameApplication'),
    SceneCoordinator: Symbol('SceneCoordinator'),
    Logger: Symbol('Logger'),
    ConfigManager: Symbol('ConfigManager'),
    
    // ECS 服务
    ECSWorld: Symbol('ECSWorld'),
    FixedUpdateManager: Symbol('FixedUpdateManager'),
    CommandQueue: Symbol('CommandQueue'),
    
    // 资源服务
    BundleManager: Symbol('BundleManager'),
    NodePoolManager: Symbol('NodePoolManager'),
    AssetLoader: Symbol('AssetLoader'),
    
    // 网络服务
    NetworkManager: Symbol('NetworkManager'),
    WebSocketClient: Symbol('WebSocketClient'),
    
    // UI 服务
    UIManager: Symbol('UIManager'),
    DialogManager: Symbol('DialogManager'),
    
    // 音频服务
    AudioManager: Symbol('AudioManager'),
    
    // 自定义服务可以继续添加...
} as const;

/**
 * 辅助函数：注册所有服务
 */
export function registerServices(): void {
    Log.styled('━'.repeat(60), 'separator');
    Log.styled('📦 注册 DI 服务', 'title');
    Log.styled('━'.repeat(60), 'separator');
    
    // 这里会自动注册所有使用 @Injectable 装饰器的类
    
    Log.styled('✅ 服务注册完成', 'success');
    Log.styled('━'.repeat(60), 'separator');
}

